<template>
  <div class="funnel-chart-container">
    <div ref="chartRef" :style="{ width, height }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

// 常量提取：避免硬编码，提高复用性
const DEFAULT_COLORS = [
  "#1cd389", "#668eff", "#ffc751", 
  "#ff6e73", "#8683e6", "#48bb78"
];
const ARROW_ICON = "image://";

export default {
  name: 'FunnelChart',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chartInstance: null,
      resizeHandler: null // 用于存储防抖后的resize函数
    };
  },
  mounted() {
    this.initChart();
    // 监听窗口 resize（防抖处理）
    this.resizeHandler = this.debounce(() => {
      this.handleResize();
    }, 100);
    window.addEventListener('resize', this.resizeHandler);
  },
  beforeDestroy() {
    // 清理图表实例和事件监听
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
    window.removeEventListener('resize', this.resizeHandler);
  },
  watch: {
    data: {
      handler() {
        this.updateChart();
      },
      deep: true
    }
  },
  methods: {
    /**
     * 初始化图表实例
     */
    initChart() {
      this.$nextTick(() => {
        if (!this.$refs.chartRef) return;
        this.chartInstance = echarts.init(this.$refs.chartRef);
        this.updateChart();
      });
    },

    /**
     * 更新图表数据和配置
     */
    updateChart() {
      if (!this.chartInstance || this.data.length === 0) return;

      const { data1, data2 } = this.formatChartData();
      const option = this.getChartOption(data1, data2);
      this.chartInstance.setOption(option);
    },

    /**
     * 格式化图表数据
     * @returns {Object} 包含处理后的data1和data2
     */
    formatChartData() {
      // 首先按数量大小降序排序
      const sortedData = [...this.data].sort((a, b) => (b.number || 0) - (a.number || 0));
      // 计算转化率
      const maxNumber = sortedData.length > 0 ? sortedData[0].number : 0;
      // 生成基础数据结构（根据排序后的数据）
      var values = ''
      const lineargroup = sortedData.map((item, index) => {
        if(index == 0) {
          values = 100
        }else if(index == 1) {
          values = 80
        }else if(index==2) {
          values = 60
        }else if(index == 3) {
          values =40
        }else if(index ==4) {
          values = 20
        }else {
          values = 10
        }
        // 计算透明度（从0.8开始递减）
        const opacity = Math.max(0.3, 0.8 - index * 0.1);
        const color = this.hexToRgba(DEFAULT_COLORS[index % DEFAULT_COLORS.length], opacity);
        const transparentColor = this.hexToRgba(DEFAULT_COLORS[index % DEFAULT_COLORS.length], 0);
        
        // 计算转化率（相对于第一个数据的百分比）
        const conversionRate = maxNumber > 0 ? ((item.number / maxNumber) * 100).toFixed(1) : 0;
        return {
          value: values, // 使用实际数据值
          name: item.name,
          oriname: item.oriname,
          number: item.number,
          conversionRate: conversionRate,
          color: [color, transparentColor]
        };
      });
   
  

var data1 = [];
var data2 = [];


for (var i = 0; i < lineargroup.length; i++) {
  
    var obj1 = {
        value: lineargroup[i].value,
        num: lineargroup[i].number,
        name: lineargroup[i].oriname
    };

    var obj2 = {
        value: lineargroup[i].value,
        name: lineargroup[i].name,
         conversionRate: lineargroup[i].conversionRate,
        itemStyle: {
            normal: {
                color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [{
                    offset: 0,
                    color: lineargroup[i].color[0]
                }, {
                    offset: 1,
                    color: lineargroup[i].color[1]
                }]),
                borderWidth: 0,
                opacity: 1
            }
        },
    };
    data1.push(obj1);
    data2.push(obj2);
}

      // const data2 = lineargroup.map(item => ({
      //   value: item.conversionRate,
      //   name: item.name,
      //   conversionRate: item.conversionRate,
      //   itemStyle: {
      //     normal: {
      //       color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
      //         { offset: 0, color: item.color[0] },
      //         { offset: 1, color: item.color[1] }
      //       ]),
      //       borderWidth: 0,
      //       opacity: 1
      //     }
      //   }
      // }));

      return { data1, data2 };
    },

    /**
     * 获取图表配置项
     * @param {Array} data1 第一个漏斗的数据
     * @param {Array} data2 第二个漏斗的数据
     * @returns {Object} echarts配置项
     */
    getChartOption(data1, data2) {
      console.log(data1,'dadas')
      const dataLength = this.data.length;
      return {
        backgroundColor: '#ffffff',
        color: DEFAULT_COLORS,
       grid: {
        top: '-11px',
        height: "436",
        bottom: '0',
        left:'12%',
        right:'20px'
    },
        xAxis: { show: false },
        yAxis: [{
          show: false,
          boundaryGap: false,
          type: 'category',
          data: Array(dataLength).fill('转化率') // 动态生成y轴数据
        }],
        series: [
          // 第一个漏斗系列
          {
            top: 0,
            type: 'funnel',
            height: '500',
            gap: 20,
            minSize: 150,
            left: '15%',
            width: '80%',
            label: {
              show: true,
              position: 'inside',
              fontSize: '14',
              formatter: d => `${d.name}{aa|}\n${d.data.num}`,
              rich: {
                aa: { padding: [8, 0, 6, 0] }
              }
            },
            data: data1
          },
          // 第二个漏斗系列
          {
            top: 0,
            type: 'funnel',
            height: '500',
            gap: 20,
            minSize: 140,
            left: '3%',
            width: '80%',
            z: 2,
            label: {
              normal: {
                color: '#333',
                position: 'insideLeft',
                padding: [11, 15],
                formatter: d => `{aa|${d.name}}\n{bb|${d.data.conversionRate}%}`,
                rich: {
                  aa: {
                    align: 'center',
                    color: '#666',
                    fontSize: '12',
                    lineHeight: '30'
                  },
                  bb: {
                    align: 'center',
                    color: '#333',
                    fontSize: '18'
                  }
                }
              }
            },
            data: data2
          },
          // 箭头系列（数量根据数据长度动态调整）
          {
            type: 'pictorialBar',
            symbolSize: ['32', '17'],
            symbolPosition: 'center',
            symbol: ARROW_ICON,
            animation: true,
            symbolClip: true,
            z: 10,
            data: Array(Math.max(0, dataLength - 1)).fill({ value: 100 })
          }
        ]
      };
    },

    /**
     * 处理窗口大小变化
     */
    handleResize() {
      this.chartInstance?.resize();
    },

    /**
     * 防抖函数
     * @param {Function} fn 要执行的函数
     * @param {Number} delay 延迟时间(ms)
     * @returns {Function} 防抖后的函数
     */
    debounce(fn, delay) {
      let timer = null;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    },

    /**
     * 十六进制颜色转rgba
     * @param {String} hex 十六进制颜色
     * @param {Number} opacity 透明度(0-1)
     * @returns {String} rgba颜色
     */
    hexToRgba(hex, opacity) {
      const r = parseInt(hex.slice(1, 3), 16);
      const g = parseInt(hex.slice(3, 5), 16);
      const b = parseInt(hex.slice(5, 7), 16);
      return `rgba(${r}, ${g}, ${b}, ${opacity})`;
    }
  }
};
</script>

<style lang="scss" scoped>
.funnel-chart-container {
  .chart-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #333;
    text-align: center;
  }
}
</style>